package com.wemei.auto.ui.utils

import android.app.Activity
import android.app.Application
import android.os.Bundle
import kotlin.system.exitProcess

object ActivityManger : Application.ActivityLifecycleCallbacks {
    private val store: MutableList<Activity> = mutableListOf()
    fun size() = store.size
    fun getCurActivity() = store[Math.max(store.size - 1, 0)]
    fun getActivity(activity: Class<*>): Activity? = store.find { store::class.java == activity }
    fun isExistence(exclude: Class<*>): Boolean {
        store.forEach {
            if (it.javaClass == exclude)
                return true
        }
        return false
    }

    fun finishAllExcludeActivity(exclude: Activity? = null) {
        var activity: Activity
        for (index in store.size - 1 downTo 0) {
            activity = store[index]
            try {
                if (activity != exclude) {
                    activity.finish()
                }
            } catch (e: Exception) {
            }
        }
    }

    fun finishAllActivity(exclude: Class<*>? = null) {
        var activity: Activity
        for (index in store.size - 1 downTo 0) {
            activity = store[index]
            try {
                if (activity.javaClass != exclude) {
                    activity.finish()
                }
            } catch (e: Exception) {
            }
        }
    }

    fun exit() {
        try {
            finishAllActivity()
            System.gc()
        } catch (e: Exception) {
        } finally {
//            MobclickAgent.onProfileSignOff()
//            SophixManager.getInstance().killProcessSafely()
//            MobclickAgent.onKillProcess(App.getApp())
            android.os.Process.killProcess(android.os.Process.myPid())
            exitProcess(0)
        }
    }

    fun registerActivityLifecycleCallbacks(application: Application) = application.registerActivityLifecycleCallbacks(this)
    override fun onActivityDestroyed(activity: Activity) {
        store.remove(activity)
    }

    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
        store.add(activity)
    }

    override fun onActivityPaused(activity: Activity) {}
    override fun onActivityStarted(activity: Activity) {}
    override fun onActivityResumed(activity: Activity) {}
    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}
    override fun onActivityStopped(activity: Activity) {}
}